package com.yuma.websocket_demo.controller;

import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.web.bind.annotation.RestController;


//   ws://localhost:10000/ws/123
@RestController
@ServerEndpoint("/ws/{userId}")  // !注解使用@ServerEndpoint注解，2.请求路径/开头
public class WebSocketController {

    @OnOpen
    public void open(@PathParam("userId") String userId) {
        System.out.println(userId + "连接成功");
    }

    @OnClose
    public void close(@PathParam("userId") String userId) {
        System.out.println(userId + "连接关闭");
    }

    @OnMessage
    public void message(String message, @PathParam("userId") String userId, Session session) {
        System.out.println("接收到来自" + userId + "的消息：" + message);
        // session就是和当前客户端的链接会话
        session.getAsyncRemote().sendText("服务器：我收到了你发来的信息");
    }

    @OnError
    public void error(Throwable error) {
        error.printStackTrace();
    }

}
